import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable }              from 'rxjs/Observable';
import { of }                      from 'rxjs/observable/of';
import { catchError, map, tap }    from 'rxjs/operators';

import { Menu }       from './menu';        // 模型名
// 删除假数据 import { MENUS }      from './mock-menus';

import { MessageService }          from './message.service';


const httpOptions = {
    // 创建对象名
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class MenuService {

  // 自来内存假数据
  private heroesUrl = 'api/menusData';  // URL to web api

  // 构造器
  constructor(
      private http: HttpClient,
      private messageService: MessageService) { }

  // 方法名   可观察数据  模型名
  getMenus(): Observable<Menu[]> {
      return this.http.get<Menu[]>(this.heroesUrl)
      .pipe(
        tap(menus => this.log(`fetched menus`)),
        catchError(this.handleError('getMenus', []))
      );
  }

  // 处理错误
  private handleError<T> (operation = 'operation', result?: T) {
      return (error: any): Observable<T> => {

        // TODO: send the error to remote logging infrastructure
        console.error(error); // log to console instead

        // TODO: better job of transforming error for user consumption
        this.log(`${operation} failed: ${error.message}`);

        // Let the app keep running by returning an empty result.
        return of(result as T);
      };
  }

  // 日志
  private log(message: string) {
      this.messageService.add('MenuService: ' + message);
  }

}
